import PostalMime from 'postal-mime';
import { Env } from './types';
import app from './router';
import { extractTextFromHTML, summarize } from './utils';
import { addDraft } from './wechat';

/**
 * Welcome to Cloudflare Workers! This is your first worker.
 *
 * - Run `npm run dev` in your terminal to start a development server
 * - Open a browser tab at http://localhost:8787/ to see your worker in action
 * - Run `npm run deploy` to publish your worker
 *
 * Learn more at https://developers.cloudflare.com/workers/
 */

export default {
	async email(message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) {
		const rawEmail = await new Response(message.raw).text();
		const parsedEmail = await PostalMime.parse(rawEmail);
		const html = parsedEmail.html || parsedEmail.text || '';
		const now = Date.now().toString();
		await env.KV.put(now, html);
		const text = extractTextFromHTML(html);
		const md = await summarize(text, env.OPENROUTER_API_KEY);
		console.log(md);
		await env.KV.put(now + '_zh', md);
		await addDraft(env, {
			title: md.split('\n\n')[0].replace('# ', ''),
			content: md,
		});
	},
	fetch: app.fetch,
	scheduled: async (controller: ScheduledController, env: Env, ctx: ExecutionContext) => {},
};
